package com.bds.btcdc.web.service;

import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.web.model.TUser;
import com.bds.btcdc.web.model.UserMO;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.DESUtil;
import com.bds.btcdc.web.utils.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

/**
 * Created by DongChenchen on 2018/4/17 0017
 */
@Service
public class UserService extends BaseService<TUser>{
	private Logger LOGGER = org.apache.log4j.Logger.getLogger(UserService.class);
	@Resource
	private NutDao dao;

	public Result login(HttpServletRequest request, HttpServletResponse response) {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		return login(email, password, request, response);
	}

	public Result login(UserMO userMO, HttpServletRequest request, HttpServletResponse response) {
		String email = userMO.getEmail();
		String password = userMO.getPassword();
		return login(email, password, request, response);
	}

	public Result login(String email, String password, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		TUser u = null;

		try {
			if (password == null || password.equals("")) {
				u = getCurrentUserInfo(request);
			} else {
				Sql sql = Sqls.create("select a.* from t_user a " + "where (a.email=@email or a.username=@username) "
						+ "and password=@password and STATUS=1");
				sql.setParam("email", email).setParam("username", email).setParam("password", MD5Util.MD5(password));
				sql.setCallback(Sqls.callback.entities());
				sql.setEntity(dao.getEntity(TUser.class));
				dao.execute(sql);
				List<TUser> users = sql.getList(TUser.class);
				if (CollectionUtils.isEmpty(users)) {
				} else if (users.size() > 1) {
					ret.setResult(Const.FAIL, "存在多用户！！");
				} else {
					u = users.get(0);
				}
			}

			if (u != null) {
				ret.setResult(Const.SUC, "登陆成功");
			} else {
				ret.setResult(Const.FAIL, "用户或者密码错误");
			}
		} catch (Exception e) {
			ret.setResult(Const.FAIL, "检查用户名密码出错");
			LOGGER.error("检查用户名密码出错", e);

		}
		ret.setData(u);
		return ret;
	}

	/**
	 * 获取当前用户 根据用户cookies里的email,查找用户
	 * 
	 * @param request
	 * @return
	 */
	public TUser getCurrentUserInfo(HttpServletRequest request) {
		TUser user = null;

		try {
			Cookie[] cookies = request.getCookies();
			if (cookies == null || cookies.length == 0) {
				return user;
			}

			for (int i = 0; i < cookies.length; ++i) {
				if (Const.COOKIES_USER_KEY.equalsIgnoreCase(cookies[i].getName())) {
					String token = cookies[i].getValue();
					if (!StringUtils.isEmpty(token)) {
						Charset CHARSET = Charset.forName("utf-8");
						String email = DESUtil.decrypt(token, CHARSET, Const.DESKEY);
						Sql sql = Sqls.create("select a.* from t_user a "
								+ "where (a.email=@email or a.username=@username) " + "and STATUS=1");
						sql.setParam("email", email).setParam("username", email);
						sql.setCallback(Sqls.callback.entities());
						sql.setEntity(dao.getEntity(TUser.class));
						dao.execute(sql);
						user = sql.getObject(TUser.class);
						if (user != null) {
							return user;
						}
					}
				}
			}
		} catch (Exception e) {
			// logger.error(var6.getMessage(), new Throwable(var6));
		}

		return user;
	}

	public boolean signUp(String username, String password, String email) {
		List<TUser> query = dao.query(TUser.class, Cnd.where("username", "=", username));
		if (query != null && query.size() == 0) {
			TUser user = new TUser();
			user.setUsername(username);
			user.setPassword(MD5Util.MD5(password));
			user.setEmail(email);
			user.setStatus(1);
			user.setCreate_time(new Date());
			dao.fastInsert(user);
			return true;
		} else {
			return false;
		}
	}
}
